package com.example.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.common.constant.CartConstant;
import com.example.common.utils.R;
import com.example.gulimall.cart.feign.ProductFeignService;
import com.example.gulimall.cart.interceptor.CartInterceptor;
import com.example.gulimall.cart.service.CartService;
import com.example.gulimall.cart.to.UserInfoTo;
import com.example.gulimall.cart.vo.CartItemVo;
import com.example.gulimall.cart.vo.CartVo;
import com.example.gulimall.cart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * 购物车业务层
 *
 * @author gulin
 * @date 2021/8/17 11:05
 */
@Slf4j
@Service("cartService")
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    CartService cartService;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    ProductFeignService productFeignService;

    /**
     * 获取登陆或者未登陆购物车所有信息
     *
     * @return: com.example.gulimall.cart.vo.CartVo
     * @author gulin
     * @date 11:07 2021/8/17
     **/
    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cartVo = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (null != userInfoTo.getUserId()) {
            //1.登陆
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
            //临时购物车的Key
            String temptCartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            //2、如果临时购物车的数据还未进行合并
            List<CartItemVo> tempCartItems = getCartItems(temptCartKey);
            if(null != tempCartItems && tempCartItems.size() >0){
                //临时购物车有数据需要进行合并操作
                for (CartItemVo cartItem : tempCartItems) {
                    this.addToCart(cartItem.getSkuId(),cartItem.getCount());
                }
                //清除临时购物车的数据
                clearCartInfo(temptCartKey);
            }
            //3、获取登录后的购物车数据【包含合并过来的临时购物车的数据和登录后购物车的数据】
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);

        } else {
            //没登录
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车所有购物信息
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);
        }
        return cartVo;
    }

    @Override
    public void clearCartInfo(String temptCartKey) {
        redisTemplate.delete(temptCartKey);
    }

    /**
     * 获取购物车里面的数据
     *
     * @param cartKey
     * @return: java.util.List<com.example.gulimall.cart.vo.CartItemVo>
     * @author gulin
     * @date 11:22 2021/8/17
     **/
    private List<CartItemVo> getCartItems(String cartKey) {
        //获取购物车里面的所有商品
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = boundHashOps.values();
        if(null != values && values.size() > 0){
            List<CartItemVo> collect = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItemVo cartItem = JSON.parseObject(str, CartItemVo.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 将商品添加至购物车
     *
     * @param skuId 商品ID
     * @param num   数量
     * @return: com.example.gulimall.cart.vo.CartItemVo 购物项
     * @author gulin
     * @date 11:15 2021/8/17
     **/
    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        //获取需要操作的购物车
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //判断该商品ID是否有货品信息
        String productRedisValue = (String) cartOps.get(skuId);
        //如果为空则添加商品-购物车
        if (StringUtils.isBlank(productRedisValue)) {
            //添加新的商品到购物车(redis)
            CartItemVo cartItemVo = new CartItemVo();
            //开启第一个任务
            CompletableFuture<Void> getSkuInfoFuture = CompletableFuture.runAsync(() -> {
                R info = productFeignService.getInfo(skuId);
                SkuInfoVo infoData = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                //数据赋值操作
                cartItemVo.setSkuId(infoData.getSkuId());
                cartItemVo.setTitle(infoData.getSkuTitle());
                cartItemVo.setImage(infoData.getSkuDefaultImg());
                cartItemVo.setPrice(infoData.getPrice());
                cartItemVo.setCount(num);
            }, executor);

            //开启第二个任务
            CompletableFuture<Void> getSkuAttrValuesFuture = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttrValues(skuSaleAttrValues);
            }, executor);
            //执行任务
            CompletableFuture.allOf(getSkuInfoFuture, getSkuAttrValuesFuture).get();
            String jsonString = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(), jsonString);
            return cartItemVo;
        } else {
            //不为空则只修改商品数量信息
            CartItemVo cartItemVo = JSON.parseObject(productRedisValue, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
            //更新Redis
            String jsonString = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(), jsonString);
            return cartItemVo;
        }
    }

    /**
     * 获取到我们要操作的购物车信息
     *
     * @return: org.springframework.data.redis.core.BoundHashOperations<java.lang.String, java.lang.Object, java.lang.Object>
     * @author gulin
     * @date 14:26 2021/8/17
     **/
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //先得到当前用户购物车信息
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        String cartKey = "";
        if (null != userInfoTo.getUserId()) {
            //如果用户登陆了使用他的userID
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
        } else {
            //否则使用临时用户标识
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
        }
        //绑定指定的key操作Redis
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }

    @Override
    public CartItemVo getCartItem(Long skuId) {
        //拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String redisValue = (String) cartOps.get(skuId.toString());

        CartItemVo cartItemVo = JSON.parseObject(redisValue, CartItemVo.class);

        return cartItemVo;
    }
}
